package clue

import (
	"git.mycaigou.com/gfyx/common/authorize"
	reportDto "git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/dto/oppty/report"
	"git.mycaigou.com/gfyx/micro-gfyx-api/service/clue"
	"io"
	"strconv"
	"strings"

	"encoding/json"
	"git.mycaigou.com/gfyx/micro-gfyx-api/http_server/controller"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/common/errcode"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/dto"
	"git.myscrm.cn/golang/stark/v4"
	"github.com/gin-gonic/gin"
)

/**
商机报备控制器
*/

type ReportController struct {
	controller.BaseController
	reportService clue.ReportServiceIface
}

func NewReportController(reportService clue.ReportServiceIface) *ReportController {
	return &ReportController{
		reportService: reportService,
	}
}

func (c *ReportController) RegisterRouter(g *gin.RouterGroup) {
	g.POST("/save", c.Save)
	g.GET("/get-report-source-info", c.GetReportSourceInfo)
	g.POST("/get-my-list", c.GetMyList)
	g.POST("/get-region-list", c.GetRegionList)
	g.GET("/search-contacts", c.SearchContacts)
	g.GET("/detail", c.GetReport)
	g.GET("/get-team-leader", c.GetTeamLeader)
	g.GET("/get-user-list", c.GetReportUser)
}

func (c *ReportController) SearchContacts(ctx *gin.Context) {

	request := &reportDto.ReportOptionRequest{}
	request.OrganizingCode = ctx.Query("organizing_code")
	request.ClueSource = ctx.Query("clue_source")
	request.ClueSourceId = ctx.Query("clue_source_id")
	request.Keyword = ctx.Query("keyword")
	page, err := strconv.Atoi(ctx.Query("page"))
	if err != nil {
		stark.Logger.Errorf(ctx, "错误code:", errcode.COMMON_PARAMS_ERROR, ",错误msg:,", err)
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "没有传递page")
		return
	}
	request.Page = int32(page)
	pageSize, err := strconv.Atoi(ctx.Query("page_size"))
	if err != nil {
		stark.Logger.Errorf(ctx, "错误code:", errcode.COMMON_PARAMS_ERROR, ",错误msg:,", err)
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "没有传递page_size")
		return
	}
	request.PageSize = int32(pageSize)

	report, err := c.reportService.SearchContacts(ctx, request)
	if err != nil {
		stark.Logger.Errorf(ctx, "ReportInfo-error: %+v, CODE: %s", err.Error(), request.ClueSource, request.ClueSourceId)
		c.Fail(ctx, errcode.COMMON_DATA_NOT_EXIST, err.Error())
		return
	}

	c.Success(ctx, report.Data)
}

func (c *ReportController) GetMyList(ctx *gin.Context) {
	// 检查数据数据
	var requestDto dto.ReportMyListRequestDto
	err := ctx.ShouldBind(&requestDto)
	if err != nil {
		stark.Logger.Errorf(ctx, "GetMyList param trans failed , err:%+v", err.Error())
		c.Fail(ctx, errcode.REPORT_MY_LIST_TRANS_FAILED, "结构体转换失败")
		return
	}
	list, err := c.reportService.GetMyReportList(ctx, &requestDto)
	if err != nil {
		stark.Logger.Errorf(ctx, "GetMyList param get data failed , err:%+v", err.Error())
		c.Fail(ctx, errcode.REPORT_MY_LIST_GET_RECORD, "获取数据失败")
		return
	}
	c.Success(ctx, list)
	return
}

func (c *ReportController) GetRegionList(ctx *gin.Context) {
	var requestDto dto.ReportMyListRequestDto
	err := ctx.ShouldBind(&requestDto)
	if err != nil {
		stark.Logger.Errorf(ctx, "GetRegionList param trans failed , err:%+v", err.Error())
		c.Fail(ctx, errcode.REPORT_MY_LIST_TRANS_FAILED, "结构体转换失败")
		return
	}
	list, err := c.reportService.GetRegionReportList(ctx, &requestDto)
	if err != nil {
		stark.Logger.Errorf(ctx, "GetRegionList param get data failed , err:%+v", err.Error())
		c.Fail(ctx, errcode.REPORT_MY_LIST_GET_RECORD, "获取数据失败:")
		return
	}
	c.Success(ctx, list)
	return
}

// @Summary 报备信息保存
// @ID save
// @Tag 报备
// @Accept json
// @Param body string true xxx
// @Param body string true xxx
// @Param body string true xxx
// @Success 200 {object} Data
func (c *ReportController) Save(ctx *gin.Context) {
	var params = make(map[string]interface{})
	//err := json.NewDecoder(ctx.Request.Body).Decode(&params)
	body, err := io.ReadAll(ctx.Request.Body)
	if err != nil {
		stark.Logger.Errorf(ctx, "读取request body出错，err:%v", err)
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, err.Error())
		return
	}
	err = json.Unmarshal(body, &params)
	if err != nil {
		stark.Logger.Errorf(ctx, "post参数json decode失败，err:%v", err)
		c.Fail(ctx, errcode.COMMON_ERROR, err.Error())
		return
	}
	//检查来源是否合法
	authType := []string{"", "CLUE", "DEVELOPER", "SUPPLIER", "PURCHASE", "WINBID", "LAND", "BUILDING", "PROJECT", "SALE"}
	if _, ok := params["clue_source"]; !ok {
		params["clue_source"] = ""
	}
	flag := false
	for _, val := range authType {
		if params["clue_source"] == val {
			flag = true
			break
		}
	}
	params["responsible_person_guid"] = ctx.Value(authorize.TENANT_USER_ID)
	params["responsible_person_name"] = ctx.Value(authorize.TENANT_USER_NAME)
	params["responsible_person_mobile"] = ctx.Value(authorize.MOBILE_PHONE)

	if !flag {
		stark.Logger.Warnf(ctx, "clue_source不合法")
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "报备来源类型错误")
		return
	}

	flag, err = c.reportService.Save(ctx, params)
	if err != nil {
		if !strings.Contains(err.Error(), "报备已存在") {
			stark.Logger.Errorf(ctx, "Save 报备保存失败，错误信息：%s", err.Error())
		}
		c.Fail(ctx, errcode.COMMON_ERROR, err.Error())
		return
	}

	c.Success(ctx, flag)
}

// @Summary 获取报备来源信息
func (c *ReportController) GetReportSourceInfo(ctx *gin.Context) {
	sourceType := ctx.Query("source_type")
	sourceId := ctx.Query("source_id")
	authType := []string{"", "CLUE", "DEVELOPER", "SUPPLIER", "PURCHASE", "WINBID", "LAND", "BUILDING", "PROJECT", "SALE"}
	flag := false
	for _, val := range authType {
		if sourceType == val {
			flag = true
			break
		}
	}
	if !flag {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "报备来源类型错误")
		return
	}

	if sourceType != "" && sourceId == "" {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "source_id不能为空")
		return
	}

	data, err := c.reportService.GetReportSourceInfo(ctx, sourceType, sourceId)
	if err != nil {
		c.Fail(ctx, errcode.COMMON_ERROR, err.Error())
		return
	}

	c.Success(ctx, data)
}

func (c *ReportController) GetReport(ctx *gin.Context) {
	reportId := ctx.Query("report_id")
	data, err := c.reportService.GetReport(ctx, reportId)
	if err != nil {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, err.Error())
		return
	}
	c.Success(ctx, data)
}

// @Summary 获取报备负责人团队
func (c *ReportController) GetTeamLeader(ctx *gin.Context) {
	reportId := ctx.Query("report_id")
	if reportId == "" {
		stark.Logger.Warnf(ctx, "report_id不能为空")
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "report_id不能为空")
		return
	}

	result, err := c.reportService.GetTeamLeader(ctx, reportId)
	if err != nil {
		stark.Logger.Errorf(ctx, "获取报备负责团队错误，错误信息：%v", err)
		c.Fail(ctx, errcode.COMMON_ERROR, err.Error())
		return
	}
	c.Success(ctx, result)
}

func (c *ReportController) GetReportUser(ctx *gin.Context) {
	result, err := c.reportService.GetReportUserList(ctx)
	if err != nil {
		stark.Logger.Errorf(ctx, "获取用户信息列表错误，错误信息：%v", err)
		c.Fail(ctx, errcode.COMMON_ERROR, err.Error())
		return
	}
	c.Success(ctx, result["list"])
}
